#!/bin/bash

# Token自动刷新功能测试脚本

echo "=== Token自动刷新功能测试 ==="
echo ""

# 设置基础URL
BASE_URL="http://localhost:8080"

echo "1. 测试用户登录获取token..."
echo "请求: POST $BASE_URL/baoyang/user/login"
echo "请求体: {\"username\":\"testuser\",\"password\":\"123456\"}"
echo ""

# 登录获取token
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/baoyang/user/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"testuser","password":"123456"}')

echo "登录响应: $LOGIN_RESPONSE"
echo ""

# 提取token
TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"data":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "❌ 登录失败，无法获取token"
    exit 1
fi

echo "✅ 成功获取token: ${TOKEN:0:20}..."
echo ""

echo "2. 测试token有效性..."
echo "请求: GET $BASE_URL/test/auth"
echo ""

# 测试token有效性
AUTH_RESPONSE=$(curl -s -X GET "$BASE_URL/test/auth" \
  -H "Authorization: $TOKEN")

echo "认证响应: $AUTH_RESPONSE"
echo ""

echo "3. 测试token刷新功能..."
echo "请求: GET $BASE_URL/test/refresh"
echo ""

# 测试token刷新
REFRESH_RESPONSE=$(curl -s -X GET "$BASE_URL/test/refresh" \
  -H "Authorization: $TOKEN")

echo "刷新响应: $REFRESH_RESPONSE"
echo ""

echo "4. 再次测试token有效性（验证刷新后仍然有效）..."
echo "请求: GET $BASE_URL/test/auth"
echo ""

# 再次测试token有效性
AUTH_RESPONSE2=$(curl -s -X GET "$BASE_URL/test/auth" \
  -H "Authorization: $TOKEN")

echo "认证响应: $AUTH_RESPONSE2"
echo ""

echo "5. 测试公开接口（无需token）..."
echo "请求: GET $BASE_URL/test/public"
echo ""

# 测试公开接口
PUBLIC_RESPONSE=$(curl -s -X GET "$BASE_URL/test/public")

echo "公开接口响应: $PUBLIC_RESPONSE"
echo ""

echo "=== 测试完成 ==="
echo ""
echo "说明："
echo "- 如果所有响应都返回成功，说明token自动刷新功能正常工作"
echo "- 每次调用需要认证的接口时，token的过期时间都会自动重置为1小时"
echo "- 可以通过Redis客户端查看token的过期时间：TTL login:token:YOUR_TOKEN"
echo ""
echo "Redis监控命令："
echo "KEYS login:token:*"
echo "TTL login:token:$TOKEN" 